package com.app.micaihu.view.main.msgcenter.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.Html;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ClickableSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.app.micaihu.R;
import com.app.micaihu.base.AppBaseAdapter;
import com.app.micaihu.base.BaseOldActivity;
import com.app.micaihu.bean.message.MsgList;
import com.app.micaihu.bean.news.NewsEntity;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.custom.view.CustomImageView;
import com.app.micaihu.custom.view.TouchyGridView;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.utils.ImageLoadUtils;
import com.app.micaihu.view.comment.SecondaryCommentDetailActivity;
import com.app.micaihu.view.main.topic.PostDetailActivity;
import com.app.micaihu.view.main.topic.adapter.SendImageGridAdapter;
import com.app.micaihu.view.user.userinfo.activity.MyHomepageDynamicActivity;
import com.app.utils.util.ViewSizeUtils;
import com.app.utils.util.image.LoadImageUtils;
import com.app.utils.util.view.expression.listener.Clickable;
import com.app.utils.util.view.expression.view.BiaoQinTextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Guo on 2016/8/23.
 * <p>
 * 消息列表的adpater
 */
public class MsgListAdapter extends AppBaseAdapter<MsgList> implements View.OnClickListener, Clickable.ClickListener {

    private String msgType;

    //名字的点击事件
    private View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //跳转个人主页
            goToDynamicActivity(UserInforManager.getInstance().getUserInfor().getUid());
        }
    };


    public MsgListAdapter(List<MsgList> list, Context context, String msgType) {
        super(list, context);
        this.msgType = msgType;
    }


    @Override
    public View creatView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_myhome_msglisg, null);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        MsgList msgList = list.get(position);
        if (msgList != null) {
            setViewData(convertView, viewHolder, msgList, msgType);
        }

        return convertView;
    }


    /**
     * 设置数据
     *
     * @param convertView
     * @param viewHolder
     * @param msgList
     * @param type
     */
    private void setViewData(View convertView, ViewHolder viewHolder, MsgList msgList, String type) {
        //头像
//        LoadImageUtils.getInstance().loadCircleImage(viewHolder.civWhoHead, msgList.getHeadPic());
        LoadImageUtils.getInstance().loadListCircleImage(viewHolder.civWhoHead, msgList.getHeadPic());

        //昵称
        viewHolder.tvNickName.setText(msgList.getNickName());
        viewHolder.tvNickName.setTextColor(convertView.getContext().getResources().getColor(R.color.userinfor_text_color));
//        LoadImageUtils.getInstance().loadImage(viewHolder.civNewsTypeIcon,msgList.getIcon());
        viewHolder.tvPublish.setText(msgList.getPublishTime());
        viewHolder.tvArticleTitle.setPicText("[" + msgList.getTypeName() + "] " + msgList.getArticleTitle());

        if (com.blankj.utilcode.util.StringUtils.isEmpty(msgList.getHonourPic())) {
            viewHolder.ivHonourPic.setVisibility(View.GONE);
        } else {
            viewHolder.ivHonourPic.setVisibility(View.VISIBLE);
            ImageLoadUtils.loadImage(msgList.getHonourPic(), viewHolder.ivHonourPic);
        }
        viewHolder.tvArmyGroupInfo.setText(msgList.getArmyGroupInfo());

        //设置军衔的隐藏，
        viewHolder.llRankContainer.setVisibility(View.VISIBLE);
        //加载军衔图标
        viewHolder.tvRankName.setText(msgList.getRankName());
        LoadImageUtils.getInstance().loadImage(viewHolder.civRankIcon, msgList.getRankIcon());

        //我的 评论的隐藏
        viewHolder.tvUserComment.setVisibility(View.GONE);
        //资讯类型图标的显示
        viewHolder.civNewsTypeIcon.setVisibility(View.VISIBLE);
        //资讯标题的显示
        viewHolder.tvArticleTitle.setVisibility(View.VISIBLE);

        viewHolder.lineDivider.setVisibility(View.VISIBLE);
        viewHolder.spanDivider.setVisibility(View.GONE);

        switch (type) {
            case TypeConstant.MSG_NOTICE://系统通知
                viewHolder.llRankContainer.setVisibility(View.GONE);
                viewHolder.civNewsTypeIcon.setVisibility(View.GONE);
                viewHolder.tvArticleTitle.setVisibility(View.GONE);
                viewHolder.tvCommentContent.setPicText(msgList.getComment());
                break;
            case TypeConstant.MSG_AT://@我的
                viewHolder.civNewsTypeIcon.setVisibility(View.GONE);
                setClickableName(viewHolder, msgList);
                break;
            case TypeConstant.MSG_COMMENT://评论我的
                viewHolder.lineDivider.setVisibility(View.GONE);
                viewHolder.spanDivider.setVisibility(View.VISIBLE);
                LoadImageUtils.getInstance().loadImage(viewHolder.civNewsTypeIcon, msgList.getIcon());
                viewHolder.tvCommentContent.setPicText(msgList.getComment());
                break;
            case TypeConstant.MSG_ZAN://赞我的
                viewHolder.civNewsTypeIcon.setVisibility(View.GONE);
                viewHolder.tvCommentContent.setPicText(context.getString(R.string.msg_zan_content));
                break;
        }


        float measureText = viewHolder.paint.measureText(msgList.getComment());
        if (measureText > ViewSizeUtils.getWidthPixels() * 3) {
            viewHolder.tvOpen.setVisibility(View.VISIBLE);
        } else {
            viewHolder.tvOpen.setVisibility(View.GONE);
        }


        if (!TextUtils.isEmpty(msgList.getParentContent())) {
            viewHolder.tvUserComment.setVisibility(View.VISIBLE);
            setSpanStr(viewHolder.tvUserComment, msgList);
        }


        List<String> contentThumbList = msgList.getContentThumbList();

        if (contentThumbList == null || contentThumbList.isEmpty()) {
            viewHolder.gridView.setVisibility(View.GONE);
            viewHolder.gridView.setOnItemClickListener(null);
        } else {
            viewHolder.gridView.setVisibility(View.VISIBLE);
            viewHolder.gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    NewsEntity newsEntity = new NewsEntity();
                    newsEntity.setArticleId(msgList.getArticleId());
                    newsEntity.setArticleType(msgList.getArticleType());
                    newsEntity.setJumpUrl(msgList.getJumpUrl());
                    TypeConstant.openTypeDetail(newsEntity, (Activity) context, TypeConstant.SOURCETYPE_SYSMSG);
                }
            });
            viewHolder.gridView.setOnNoItemClickListener(new TouchyGridView.OnNoItemClickListener() {
                @Override
                public void onNoItemClick() {
                    NewsEntity newsEntity = new NewsEntity();
                    newsEntity.setArticleId(msgList.getArticleId());
                    newsEntity.setArticleType(msgList.getArticleType());
                    newsEntity.setJumpUrl(msgList.getJumpUrl());
                    TypeConstant.openTypeDetail(newsEntity, (Activity) context, TypeConstant.SOURCETYPE_SYSMSG);
                }
            });
            viewHolder.gridView.setTag(contentThumbList);
            if (contentThumbList.size() > 3) {
                contentThumbList = contentThumbList.subList(0, 3);
            }
            if (viewHolder.gridView.getAdapter() == null) {
                SendImageGridAdapter sendImageGridAdapter = new SendImageGridAdapter(contentThumbList, context, 82.5f);
                viewHolder.gridView.setAdapter(sendImageGridAdapter);

            } else {
                //这里注意.要更新 gridview的adapter 的数据list.不然会出现服用adapter.但是数据没变的情况
                ((SendImageGridAdapter) viewHolder.gridView.getAdapter()).setList(contentThumbList);
                ((SendImageGridAdapter) viewHolder.gridView.getAdapter()).notifyDataSetChanged();
            }
        }

        //为评论内容设置tag和是否展开
        viewHolder.tvCommentContent.setTag(false);
        viewHolder.tvOpen.setTag(viewHolder.tvCommentContent);

        //为文章设置tag
        viewHolder.tvArticleTitle.setTag(msgList);

        //为头像和昵称设置tag
        viewHolder.civWhoHead.setTag(msgList.getUid());
        viewHolder.tvNickName.setTag(msgList.getUid());

        //设置item->跳转到评论内页的tag
        viewHolder.llItem.setTag(msgList);

    }

    /**
     * 设置zan中的富文本方法
     *
     * @param biaoQinTextView
     * @param msgList
     */
    private void setSpanStr(BiaoQinTextView biaoQinTextView, MsgList msgList) {

//        Drawable drawable = context.getResources().getDrawable(R.drawable.infor_articlecom_good_vis);
//        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
//                drawable.getIntrinsicHeight());
//        SpannableString spannable = new SpannableString("赞了我 " + "[zan]");
//        ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
//        spannable.setSpan(span, 4,4 + "[zan]".length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
//        if(TextUtils.equals(msgType,TypeConstant.MSG_ZAN)){
//            biaoQinTextView.setPicText(context.getString(R.string.msg_zan_content));
//        }else{
        String userComment;
        userComment = "我 <font color=\"#999999\">"
                + "评论" + msgList.getTypeName() + ": "
                + "</font>" + msgList.getParentContent();
        biaoQinTextView.setPicText(Html.fromHtml(userComment));
//        }
    }

    /**
     * 设置@的点击效果的方法
     *
     * @param viewHolder
     * @param msgList
     */
    private void setClickableName(ViewHolder viewHolder, MsgList msgList) {
        String nickName = "";
        String uid = "";
        if (UserInforManager.getInstance().isLogin()) {
            nickName = UserInforManager.getInstance().getUserInfor().getNickName();
            uid = UserInforManager.getInstance().getUserInfor().getUid();
        }

        ArrayList<String> strs = new ArrayList<>();
        ArrayList<Integer> color = new ArrayList<>();
        ArrayList<Object> parms = new ArrayList<>();
        String type = "@";
        //添加第一个参数
        if (!TextUtils.isEmpty(type)) {
            strs.add(type + nickName + " ");
            color.add(Color.parseColor("#546a93"));
            parms.add(uid);
        }
        //添加第二个参数
        strs.add(msgList.getComment());
        //日间颜色
        color.add(Color.parseColor("#ff505050"));
        parms.add(msgList);
        viewHolder.tvCommentContent.setText(strs, color, parms, this);

    }

    @Override
    public void click(int position, ArrayList<Object> parms) {
        if (parms == null) {
            return;
        }
        if (parms.size() == 1) {
            MsgList msgList;
            try {
                msgList = (MsgList) parms.get(0);
            } catch (Exception e) {
                msgList = null;
            }
            goToCommentDetail(context, msgList);
        } else if (parms.size() == 2) {
            if (position == 0) {
                String uid = parms.get(0).toString();
                //点击评论用户昵称
                Intent intent = new Intent(context, MyHomepageDynamicActivity.class);
                intent.putExtra(Config.Extra.PARAMETER1, uid);
                context.startActivity(intent);
            } else if (position == 1) {
                MsgList msgList;
                try {
                    msgList = (MsgList) parms.get(1);
                } catch (Exception e) {
                    msgList = null;
                }
                goToCommentDetail(context, msgList);
            }
        }

    }

//    @Override
//    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//        try {
//            ArrayList<String> thumbList = (ArrayList<String>) parent.getTag();
//
//            Intent intent = new Intent(parent.getContext(), ImageShowActivity.class);
//            intent.putStringArrayListExtra(BaseOldActivity.PARAMETER1, thumbList);
//            intent.putExtra(BaseOldActivity.PARAMETER2, position);
//            intent.setClass(parent.getContext(), ImageShowActivity.class);
//            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            parent.getContext().startActivity(intent);
////                overridePendingTransition(R.anim.base_alpha_in, R.anim.base_slide_remain);// 前一个参数是下一个Activity的效果

//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//    }


    class ViewHolder {
        CustomImageView civWhoHead;//评论人的头像
        TextView tvNickName;//昵称
        //CustomImageView civRankIcon;//军衔图标
        TextView tvPublish;//发布时间
        TextView tvOpen;//展开按钮
        TextView tvArmyGroupInfo;//
        ImageView ivHonourPic;//
        BiaoQinTextView tvCommentContent;//评论内容-带表情
        //CustomImageView civThumb;//文章缩略图
        BiaoQinTextView tvArticleTitle;//文章title
        //LinearLayout llArticleContent;//文章的容器
        CustomImageView civNewsTypeIcon;//文章类型的图标

        BiaoQinTextView tvUserComment;//我评论文章的内容


        // 2.0.1版本新增View 赞 部分的内容
        //军衔部分
        LinearLayout llRankContainer;//军衔view的容器
        CustomImageView civRankIcon;//军衔图标
        TextView tvRankName;//军衔名称

        //2.0.2新增需求，点击item 进入评论内页
        LinearLayout llItem;


        //202
        View spanDivider;
        View lineDivider;


        //2052
        TouchyGridView gridView;

        LinearLayout llThumbContainer;
        TextPaint paint;

        public ViewHolder(View convertView) {
            civWhoHead = (CustomImageView) convertView.findViewById(R.id.civ_whohead);
            llThumbContainer = (LinearLayout) convertView.findViewById(R.id.ll_content_and_thumb);
            tvNickName = (TextView) convertView.findViewById(R.id.tv_nickname);
            tvPublish = (TextView) convertView.findViewById(R.id.tv_publish);
            tvOpen = (TextView) convertView.findViewById(R.id.tv_open);
            tvCommentContent = (BiaoQinTextView) convertView.findViewById(R.id.tv_comment_content);
            //civThumb = (CustomImageView) convertView.findViewById(R.id.comment_news_img);
            //tvArticleTitle = (TextView) convertView.findViewById(R.id.comment_news_title);
            tvArticleTitle = (BiaoQinTextView) convertView.findViewById(R.id.tv_articletitle);
            //llArticleContent = (LinearLayout) convertView.findViewById(R.id.comment_news_layout);
            civNewsTypeIcon = (CustomImageView) convertView.findViewById(R.id.civ_newstype);

            // 2.0.1版本新增View 赞 部分的内容
            tvUserComment = (BiaoQinTextView) convertView.findViewById(R.id.tv_user_comment);
            llRankContainer = (LinearLayout) convertView.findViewById(R.id.ll_rankcontainer);
            civRankIcon = (CustomImageView) convertView.findViewById(R.id.civ_rank_icon);
            tvRankName = (TextView) convertView.findViewById(R.id.tv_rank_name);

            //2.0.2新增 点击item 进评论详情
            llItem = (LinearLayout) convertView.findViewById(R.id.ll_item);
            spanDivider = convertView.findViewById(R.id.span_divider);
            lineDivider = convertView.findViewById(R.id.line_divider);

            gridView = (TouchyGridView) convertView.findViewById(R.id.gridview);
            ivHonourPic = convertView.findViewById(R.id.ivHonourPic);
            tvArmyGroupInfo = convertView.findViewById(R.id.tvArmyGroupInfo);

//            gridView.setOnItemClickListener(MsgListAdapter.this);


            civWhoHead.setOnClickListener(MsgListAdapter.this);//头像的点击事件
            tvNickName.setOnClickListener(MsgListAdapter.this);//昵称的点击事件

            tvOpen.setOnClickListener(MsgListAdapter.this);//展开的点击事件
            //llArticleContent.setOnClickListener(MsgListAdapter.this);//文章的点击事件
            tvArticleTitle.setOnClickListener(MsgListAdapter.this);//文章的点击事件
            llItem.setOnClickListener(MsgListAdapter.this);//item的点击事件

//            ViewTreeObserver viewTreeObserver = tvCommentContent.getViewTreeObserver();
//            viewTreeObserver.addOnPreDrawListener(this);

            paint = tvCommentContent.getPaint();

        }

//        @Override
//        public boolean onPreDraw() {
//            int width = tvCommentContent.getWidth();
//            TextPaint paint = tvCommentContent.getPaint();
//            float measureText = paint.measureText(tvCommentContent.getText().toString());
//            if (measureText > width * 3) {
//                tvOpen.setVisibility(View.VISIBLE);
//            } else {
//                tvOpen.setVisibility(View.GONE);
//            }
//            return true;
//        }
    }


    @Override
    public void onClick(View v) {
        if (v == null) return;
        switch (v.getId()) {
            case R.id.ll_item://跳转到评论详情中
                Object tag1 = v.getTag();
                if (tag1 != null && tag1 instanceof MsgList) {
                    MsgList msgList = (MsgList) tag1;
                    goToCommentDetail(v.getContext(), msgList);
                }
                break;
            case R.id.civ_whohead:
            case R.id.tv_nickname://头像及昵称的点击事件->跳转至主页
                Object tag = v.getTag();
                if (tag instanceof String) {
                    String uid = (String) tag;
                    if (!TextUtils.isEmpty(uid)) {
                        goToDynamicActivity(uid);
                    }
                }

                break;
            //case R.id.comment_news_layout://文章的点击事件->跳转至文章
            case R.id.tv_articletitle://文章的点击事件->跳转至文章
                goToDetail(v);
                break;
            case R.id.tv_open://展开->将消息展开到完全体
                openOrClose(v);
                break;
        }
    }

    private void goToCommentDetail(Context context, MsgList msgList) {
        if (msgList == null || context == null) {
            return;
        }
        Intent intent1 = new Intent();
        if (TypeConstant.POST_2052.equals(msgList.getArticleType())) {
            if (TextUtils.equals(msgList.getCmtType(), TypeConstant.COMMENT_PARENT)) {
                intent1.setClass(context, PostDetailActivity.class);
                intent1.putExtra(Config.Extra.PARAMETER1, msgList.getCommentId());
            } else if (TextUtils.equals(msgList.getCmtType(), TypeConstant.COMMENT_TWO)
                    || TextUtils.equals(msgList.getCmtType(), TypeConstant.COMMENT_ONE)) {
                intent1.setClass(context, SecondaryCommentDetailActivity.class);
                intent1.putExtra(Config.Extra.PARAMETER1, msgList.getArticleId());
                intent1.putExtra(Config.Extra.PARAMETER2, msgList.getParentCmtId());
                intent1.putExtra(SecondaryCommentDetailActivity.COMMENT_OR_POST, false);
            }
        } else {
            if (TextUtils.equals(msgList.getCmtType(), TypeConstant.COMMENT_PARENT)) {
                intent1.putExtra(Config.Extra.PARAMETER2, msgList.getCommentId());
            } else if (TextUtils.equals(msgList.getCmtType(), TypeConstant.COMMENT_TWO)
                    || TextUtils.equals(msgList.getCmtType(), TypeConstant.COMMENT_ONE)) {
                intent1.putExtra(Config.Extra.PARAMETER2, msgList.getParentCmtId());
            }
            intent1.putExtra(SecondaryCommentDetailActivity.COMMENT_OR_POST, true);
            intent1.setClass(context, SecondaryCommentDetailActivity.class);
            intent1.putExtra(Config.Extra.PARAMETER1, msgList.getArticleId());

        }
        if (intent1.getComponent() != null) {
            ((Activity) context).startActivity(intent1);

        }


    }

    private void goToDetail(View v) {
        if (v.getTag() == null) return;
        MsgList msgList = (MsgList) v.getTag();
        if (msgList == null) return;
        NewsEntity newsEntity = new NewsEntity();
        newsEntity.setArticleId(msgList.getArticleId());
        newsEntity.setArticleType(msgList.getArticleType());
        newsEntity.setJumpUrl(msgList.getJumpUrl());
        TypeConstant.openTypeDetail(newsEntity, (Activity) context, TypeConstant.SOURCETYPE_SYSMSG);
    }


    /**
     * 关闭/打开扩展的消息
     *
     * @param v
     */
    private void openOrClose(View v) {
        if (v instanceof TextView) {
            Object tag = v.getTag();
            if (tag instanceof TextView) {
                TextView tv = (TextView) tag;
                boolean isExpend = (boolean) tv.getTag();
                if (!isExpend) {
                    // 复原
                    tv.setMinLines(0);
                    tv.setMaxLines(Integer.MAX_VALUE);
                    tv.setTag(true);

                    ((TextView) v).setText("收起");
                } else {
                    tv.setMaxLines(3);
                    tv.setTag(false);
                    ((TextView) v).setText("展开");
                }
            }
        }
    }


    class Clickable extends ClickableSpan {
        private final View.OnClickListener mListener;

        public Clickable(View.OnClickListener l) {
            mListener = l;
        }

        @Override
        public void onClick(View widget) {
            mListener.onClick(widget);
        }

        @Override
        public void updateDrawState(TextPaint ds) {

            ds.setColor(context.getResources().getColor(R.color.common_font_color_8));
        }
    }


    /**
     * 跳转到个人主页
     *
     * @param uid
     */
    private void goToDynamicActivity(String uid) {
        Intent intent = new Intent(context, MyHomepageDynamicActivity.class);
        intent.putExtra(Config.Extra.PARAMETER1, uid);
        context.startActivity(intent);
    }
}
